import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { Response, Request } from 'express';

@Catch()
export class HttpExceptionFilter<T> implements ExceptionFilter {
    catch(exception: T | any, host: ArgumentsHost) {
        const context = host.switchToHttp();
        const request = context.getRequest<Request>();
        const response = context.getResponse<Response>();
        const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
        const message = exception?.message || exception?.message?.message || exception?.message?.error;
        const method = request.method;
        const errorLog = {
            status,
            description: '请求失败',
            message,
            timeStamp: `${new Date().toLocaleString()} ${Date.now()}`,
            path: request.url,
            method,
        };
        Logger.warn(errorLog);
        response.status(200).json({
            code: status || 500,
            message,
        });
    }
}
